package com.xinzhi.service.impl;

import com.xinzhi.mapper.updateUserMapper;
import com.xinzhi.pojo.dto.UserDetailsUpdateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Transactional
@Service
public class UpdateUserService {

    @Autowired
    private updateUserMapper updateUserMapper;

    // 正则表达式
    private static final String LAST_NAME_REGEX = "^[\\u4E00-\\u9FA5]{1}$";
    private static final String FIRST_NAME_REGEX = "^[\\u4E00-\\u9FA5]{2}$";
    private static final String IDCARD_REGEX = "^\\d{17}[\\dX]$";

    // 已有的方法，保留
    public void updateUserInfo(String localPhoneNumber, String lastName, String firstName, String idcard) {
        // 验证输入
        validateUserInfo(lastName, firstName, idcard);


        UserDetailsUpdateRequest request = new UserDetailsUpdateRequest();
        request.setLastName(lastName);
        request.setFirstName(firstName);
        request.setIdcard(idcard);
        request.setPhone(localPhoneNumber);
        updateUserMapper.updateUserDetailsByPhone(request);
    }

    // 重载方法，直接使用UserDetailsUpdateRequest对象
    public void updateUserInfo(UserDetailsUpdateRequest userDetails) {
        // 确保request不为null
        if (userDetails != null) {
            // 验证输入
            validateUserInfo(userDetails.getLastName(), userDetails.getFirstName(), userDetails.getIdcard());

            // 校验数据库中是否已存在该手机号

            updateUserMapper.updateUserDetailsByPhone(userDetails);
        } else {
            throw new IllegalArgumentException("UserDetailsUpdateRequest 不能为空");
        }
    }

    // 验证方法
    private void validateUserInfo(String lastName, String firstName, String idcard) {
        if (lastName == null || !lastName.matches(LAST_NAME_REGEX)) {
            throw new IllegalArgumentException("姓必须为一个汉字");
        }
        if (firstName == null || !firstName.matches(FIRST_NAME_REGEX)) {
            throw new IllegalArgumentException("名必须为两个汉字");
        }
        if (idcard == null || !idcard.matches(IDCARD_REGEX)) {
            throw new IllegalArgumentException("身份证必须为18位数字，最后一位可以是数字或'X'");
        }
    }
}
